<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>收款码拼接工具</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary: #07C160;
            --primary-dark: #06ae56;
            --secondary: #1677FF;
            --secondary-dark: #1466d9;
            --tertiary: #FA6F63;
            --tertiary-dark: #e85d51;
            --light-bg: #f8f9fa;
            --card-bg: #ffffff;
            --text-primary: #333333;
            --text-secondary: #666666;
            --text-light: #888888;
            --border: #e0e0e0;
            --shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
            --radius: 12px;
            --transition: all 0.3s ease;
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
            background-color: var(--light-bg);
            color: var(--text-primary);
            line-height: 1.6;
            padding: 20px;
            min-height: 100vh;
        }

        .app-container {
            max-width: 1000px;
            margin: 0 auto;
            display: grid;
            grid-template-columns: 1fr;
            gap: 24px;
        }

        @media (min-width: 900px) {
            .app-container {
                grid-template-columns: 1fr 1fr;
            }
            
            .result-container {
                grid-column: 2;
                grid-row: 1 / span 2;
            }
        }

        .card {
            background: var(--card-bg);
            border-radius: var(--radius);
            box-shadow: var(--shadow);
            padding: 24px;
            transition: var(--transition);
        }

        .card:hover {
            box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
        }

        .header {
            text-align: center;
            margin-bottom: 24px;
        }

        .header h1 {
            font-size: 28px;
            margin-bottom: 8px;
            color: var(--text-primary);
        }

        .header p {
            color: var(--text-secondary);
            font-size: 16px;
        }

        .section-title {
            font-size: 18px;
            margin-bottom: 16px;
            color: var(--text-primary);
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .section-title i {
            color: var(--primary);
        }

        /* Layout Options */
        .layout-options {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 12px;
            margin-bottom: 20px;
        }

        .layout-option {
            border: 2px solid var(--border);
            border-radius: var(--radius);
            padding: 16px 12px;
            text-align: center;
            cursor: pointer;
            transition: var(--transition);
            background: var(--card-bg);
        }

        .layout-option:hover {
            border-color: var(--primary);
        }

        .layout-option.active {
            border-color: var(--primary);
            background-color: rgba(7, 193, 96, 0.05);
        }

        .layout-option i {
            font-size: 24px;
            margin-bottom: 8px;
            color: var(--text-light);
        }

        .layout-option.active i {
            color: var(--primary);
        }

        .layout-option span {
            font-size: 14px;
            font-weight: 500;
        }

        /* Upload Areas */
        .upload-container {
            display: grid;
            grid-template-columns: 1fr;
            gap: 16px;
            margin-bottom: 20px;
        }

        @media (min-width: 600px) {
            .upload-container {
                grid-template-columns: 1fr 1fr;
            }
        }

        .upload-box {
            border: 2px dashed var(--border);
            border-radius: var(--radius);
            padding: 20px;
            text-align: center;
            transition: var(--transition);
            background: var(--card-bg);
            position: relative;
            overflow: hidden;
        }

        .upload-box:hover {
            border-color: var(--primary);
        }

        .upload-box h3 {
            font-size: 16px;
            margin-bottom: 12px;
            color: var(--text-primary);
        }

        .upload-area {
            height: 140px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            color: var(--text-light);
            position: relative;
        }

        .upload-icon {
            font-size: 32px;
            margin-bottom: 8px;
            color: var(--primary);
        }

        .upload-text {
            font-size: 14px;
            margin-bottom: 8px;
        }

        .upload-hint {
            font-size: 12px;
            color: var(--text-light);
        }

        .upload-box img {
            max-width: 100%;
            max-height: 120px;
            object-fit: contain;
            margin-bottom: 8px;
            display: none;
        }

        .upload-box input[type="file"] {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
            cursor: pointer;
        }

        .qr-status {
            font-size: 13px;
            margin-top: 8px;
            font-weight: 500;
        }

        .status-valid {
            color: var(--primary);
        }

        .status-invalid {
            color: #ff4d4f;
        }

        /* Payment Type Selector */
        .payment-selector {
            display: flex;
            align-items: center;
            justify-content: space-between;
            background: rgba(0, 0, 0, 0.03);
            padding: 12px 16px;
            border-radius: var(--radius);
            margin: 16px 0;
        }

        .payment-selector h3 {
            font-size: 16px;
            margin: 0;
        }

        .payment-selector select {
            padding: 8px 12px;
            border-radius: 6px;
            border: 1px solid var(--border);
            background: var(--card-bg);
            font-size: 14px;
            min-width: 140px;
        }

        /* Buttons */
        .btn {
            display: inline-block;
            background-color: var(--primary);
            color: white;
            border: none;
            padding: 14px 24px;
            border-radius: var(--radius);
            font-weight: 600;
            cursor: pointer;
            transition: var(--transition);
            text-align: center;
            width: 100%;
            font-size: 16px;
        }

        .btn:hover {
            background-color: var(--primary-dark);
            transform: translateY(-2px);
        }

        .btn:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
            transform: none;
        }

        .btn-secondary {
            background-color: var(--secondary);
        }

        .btn-secondary:hover {
            background-color: var(--secondary-dark);
        }

        /* Result Area */
        .result-container {
            display: flex;
            flex-direction: column;
        }

        .result-image {
            width: 100%;
            border: 1px solid var(--border);
            border-radius: var(--radius);
            overflow: hidden;
            margin: 20px 0;
            background: white;
        }

        .result-image img {
            width: 100%;
            display: block;
        }

        .size-control {
            margin: 20px 0;
        }

        .size-title {
            font-size: 16px;
            margin-bottom: 12px;
            color: var(--text-primary);
        }

        .size-options {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 8px;
            margin-bottom: 16px;
        }

        .size-btn {
            padding: 10px 0;
            background: var(--light-bg);
            border: 1px solid var(--border);
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            text-align: center;
            transition: var(--transition);
        }

        .size-btn.active {
            background: rgba(7, 193, 96, 0.1);
            border-color: var(--primary);
            color: var(--primary);
            font-weight: 500;
        }

        .custom-size {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .custom-size input {
            flex: 1;
        }

        .custom-size span {
            min-width: 60px;
            text-align: right;
            font-size: 14px;
            color: var(--text-secondary);
        }

        /* Instructions */
        .instructions {
            background: var(--light-bg);
            padding: 16px;
            border-radius: var(--radius);
            margin: 20px 0;
        }

        .instructions h3 {
            font-size: 16px;
            margin-bottom: 12px;
            color: var(--text-primary);
        }

        .instructions ol {
            padding-left: 20px;
            color: var(--text-secondary);
        }

        .instructions li {
            margin-bottom: 8px;
            font-size: 14px;
        }

        /* Utility Classes */
        .hidden {
            display: none !important;
        }

        .mt-20 {
            margin-top: 20px;
        }

        .error-message {
            color: #ff4d4f;
            text-align: center;
            padding: 12px;
            background: rgba(255, 77, 79, 0.1);
            border-radius: var(--radius);
            margin: 16px 0;
            font-size: 14px;
        }

        /* QQ Style Selector */
        .style-selector {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 10px;
            margin-top: 12px;
        }

        .style-option {
            display: flex;
            align-items: center;
            padding: 10px;
            border: 1px solid var(--border);
            border-radius: 6px;
            cursor: pointer;
            transition: var(--transition);
        }

        .style-option input[type="radio"] {
            margin-right: 8px;
        }

        .style-option.active {
            border-color: var(--primary);
            background: rgba(7, 193, 96, 0.05);
        }

        .color-sample {
            width: 16px;
            height: 16px;
            border-radius: 50%;
            margin-right: 8px;
        }

        /* Custom name input */
        .custom-name-input {
            margin-top: 10px;
        }

        .custom-name-input input {
            width: 100%;
            padding: 10px;
            border: 1px solid var(--border);
            border-radius: 6px;
            font-size: 14px;
        }
    </style>
    <!-- 引入二维码解码和生成库 -->
    <!-- <script src="https://cdn.jsdelivr.net/npm/jsqr@1.4.0/dist/jsQR.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/qrcode@1.5.1/build/qrcode.min.js"></script> -->
    <script src="jsQR.min.js"></script>
    <script src="qrcode.min.js"></script>
</head>
<body>
    <div class="app-container">
        <div class="card">
            <div class="header">
                <h1><i class="fas fa-qrcode"></i> 收款码拼接工具</h1>
                <p>将多个支付平台的收款码拼接为一个，方便顾客扫码支付</p>
            </div>
            
            <div class="section-title">
                <i class="fas fa-th"></i>
                <span>选择布局类型</span>
            </div>
            
            <div class="layout-options">
                <div class="layout-option active" data-layout="two-grid">
                    <i class="fas fa-border-all"></i>
                    <span>二格布局</span>
                </div>
                <div class="layout-option" data-layout="three-grid">
                    <i class="fas fa-th-large"></i>
                    <span>三格布局</span>
                </div>
                <div class="layout-option" data-layout="four-grid">
                    <i class="fas fa-grid"></i>
                    <span>四格布局</span>
                </div>
            </div>
            
            <div class="section-title">
                <i class="fas fa-upload"></i>
                <span>上传收款码</span>
            </div>
            
            <div class="upload-container">
                <div class="upload-box">
                    <h3><i class="fab fa-weixin" style="color: #07C160;"></i> 微信收款码</h3>
                    <div class="upload-area">
                        <div class="upload-icon"><i class="fas fa-cloud-upload-alt"></i></div>
                        <div class="upload-text">点击上传微信收款码</div>
                        <div class="upload-hint">支持JPG, PNG格式</div>
                        <img id="wechatPreview" alt="微信收款码">
                        <input type="file" id="wechatFile" accept="image/*">
                    </div>
                    <div class="qr-status" id="wechatStatus"></div>
                </div>
                
                <div class="upload-box">
                    <h3><i class="fab fa-alipay" style="color: #1677FF;"></i> 支付宝收款码</h3>
                    <div class="upload-area">
                        <div class="upload-icon"><i class="fas fa-cloud-upload-alt"></i></div>
                        <div class="upload-text">点击上传支付宝收款码</div>
                        <div class="upload-hint">支持JPG, PNG格式</div>
                        <img id="alipayPreview" alt="支付宝收款码">
                        <input type="file" id="alipayFile" accept="image/*">
                    </div>
                    <div class="qr-status" id="alipayStatus"></div>
                </div>
                
                <div class="upload-box third-code">
                    <h3 id="thirdTypeTitle"><i class="fas fa-money-bill-wave" style="color: #FA6F63;"></i> 云闪付收款码</h3>
                    <div class="upload-area">
                        <div class="upload-icon"><i class="fas fa-cloud-upload-alt"></i></div>
                        <div class="upload-text" id="thirdPlaceholderText">点击上传云闪付收款码</div>
                        <div class="upload-hint">支持JPG, PNG格式</div>
                        <img id="thirdPreview" alt="第三方收款码">
                        <input type="file" id="thirdFile" accept="image/*">
                    </div>
                    <div class="qr-status" id="thirdStatus"></div>
                </div>
                
                <div class="upload-box fourth-code">
                    <h3 id="fourthTypeTitle"><i class="fas fa-money-bill-wave" style="color: #9C27B0;"></i> 云闪付收款码</h3>
                    <div class="upload-area">
                        <div class="upload-icon"><i class="fas fa-cloud-upload-alt"></i></div>
                        <div class="upload-text" id="fourthPlaceholderText">点击上传云闪付收款码</div>
                        <div class="upload-hint">支持JPG, PNG格式</div>
                        <img id="fourthPreview" alt="第四方收款码">
                        <input type="file" id="fourthFile" accept="image/*">
                    </div>
                    <div class="qr-status" id="fourthStatus"></div>
                </div>
            </div>
            
            <div class="payment-selector third-code">
                <h3><i class="fas fa-credit-card"></i> 选择第一个第三方支付方式</h3>
                <select id="thirdType">
                    <option value="unionpay">云闪付</option>
                    <option value="qq">QQ支付</option>
                    <option value="custom">自定义支付</option>
                </select>
            </div>
            
            <div class="custom-name-input third-code" id="thirdCustomNameContainer">
                <input type="text" id="thirdCustomName" placeholder="输入自定义支付名称">
            </div>
            
            <div class="payment-selector fourth-code">
                <h3><i class="fas fa-credit-card"></i> 选择第二个第三方支付方式</h3>
                <select id="fourthType">
                    <option value="unionpay">云闪付</option>
                    <option value="qq">QQ支付</option>
                    <option value="custom">自定义支付</option>
                </select>
            </div>
            
            <div class="custom-name-input fourth-code" id="fourthCustomNameContainer">
                <input type="text" id="fourthCustomName" placeholder="输入自定义支付名称">
            </div>
            
            <div class="style-selector third-code" id="qqStyleSelector">
                <div class="style-option active">
                    <input type="radio" name="qqStyle" value="blue" checked>
                    <span class="color-sample" style="background:#12B7F5;"></span>
                    <span>蓝色</span>
                </div>
                <div class="style-option">
                    <input type="radio" name="qqStyle" value="purple">
                    <span class="color-sample" style="background:#6A11CB;"></span>
                    <span>紫色</span>
                </div>
                <div class="style-option">
                    <input type="radio" name="qqStyle" value="green">
                    <span class="color-sample" style="background:#3CB371;"></span>
                    <span>绿色</span>
                </div>
                <div class="style-option">
                    <input type="radio" name="qqStyle" value="dark">
                    <span class="color-sample" style="background:#333333;"></span>
                    <span>深色</span>
                </div>
            </div>
            
            <div id="error" class="error-message hidden"></div>
            
            <button id="generateBtn" class="btn" disabled>生成拼接收款码</button>
        </div>
        
        <div class="card result-container">
            <div class="section-title">
                <i class="fas fa-check-circle"></i>
                <span id="resultTitle">您的收款码</span>
            </div>
            
            <div class="result-image" id="combinedQRCode">
                <div style="padding: 40px; text-align: center; color: var(--text-light);">
                    <i class="fas fa-qrcode" style="font-size: 64px; opacity: 0.3;"></i>
                    <p>生成的收款码将显示在这里</p>
                </div>
            </div>
            
            <div class="size-control">
                <div class="size-title">调整图片大小</div>
                <div class="size-options">
                    <div class="size-btn active" data-size="800">小</div>
                    <div class="size-btn" data-size="1000">中</div>
                    <div class="size-btn" data-size="1200">大</div>
                    <div class="size-btn" data-size="1500">超大</div>
                </div>
                <div class="custom-size">
                    <input type="range" id="sizeSlider" min="500" max="2000" step="100" value="800">
                    <span id="sizeValue">800px</span>
                </div>
            </div>
            
            <div class="instructions" id="twoGridInfo">
                <h3><i class="fas fa-info-circle"></i> 使用说明</h3>
                <ol>
                    <li>长按或右键保存上方二维码图片</li>
                    <li>微信用户扫描上方左侧的二维码进行支付</li>
                    <li>支付宝用户扫描下方右侧的二维码进行支付</li>
                </ol>
            </div>
            
            <div class="instructions hidden" id="threeGridInfo">
                <h3><i class="fas fa-info-circle"></i> 使用说明</h3>
                <ol>
                    <li>长按或右键保存上方三格二维码图片</li>
                    <li>微信用户扫描左上角的二维码进行支付</li>
                    <li>支付宝用户扫描右上角的二维码进行支付</li>
                    <li>云闪付/QQ用户扫描底部的二维码进行支付</li>
                </ol>
            </div>
            
            <div class="instructions hidden" id="fourGridInfo">
                <h3><i class="fas fa-info-circle"></i> 使用说明</h3>
                <ol>
                    <li>长按或右键保存上方四格二维码图片</li>
                    <li>微信用户扫描左上角的二维码进行支付</li>
                    <li>支付宝用户扫描右上角的二维码进行支付</li>
                    <li>第一个第三方支付用户扫描左下角的二维码进行支付</li>
                    <li>第二个第三方支付用户扫描右下角的二维码进行支付</li>
                </ol>
            </div>
            
            <button id="downloadBtn" class="btn btn-secondary">下载收款码</button>
        </div>
    </div>

    <script>
        // 全局变量
        var wechatImg = null;
        var alipayImg = null;
        var thirdImg = null;
        var wechatData = null;
        var alipayData = null;
        var thirdData = null;
        var currentSize = 800; // 默认大小
        var wechatQR = null;   // 缓存生成的二维码
        var alipayQR = null;   // 缓存生成的二维码
        var thirdQR = null;    // 缓存生成的二维码
        var layoutMode = "two-grid"; // 默认布局模式
        
        // 第三方支付类型
        var thirdPayType = 'unionpay';
        
        // 添加全局变量
        var fourthImg = null;
        var fourthData = null;
        var fourthQR = null;    // 缓存生成的二维码
        var fourthPayType = 'unionpay';
        
        // 自定义名称
        var thirdCustomPayName = '自定义';
        var fourthCustomPayName = '自定义';
        
        // 全局变量
        var qqStyle = 'blue'; // 默认QQ样式

        // 初始化函数
        window.onload = function() {
            console.log('页面初始化中...');
            
            // 布局选项事件
            document.querySelectorAll('.layout-option').forEach(option => {
                option.addEventListener('click', function() {
                    document.querySelectorAll('.layout-option').forEach(opt => {
                        opt.classList.remove('active');
                    });
                    this.classList.add('active');
                    setLayoutMode(this.dataset.layout);
                });
            });
            
            // 文件上传事件
            document.getElementById('wechatFile').addEventListener('change', function() {
                previewImage(this, 'wechatPreview', 'wechatStatus');
            });
            document.getElementById('alipayFile').addEventListener('change', function() {
                previewImage(this, 'alipayPreview', 'alipayStatus');
            });
            document.getElementById('thirdFile').addEventListener('change', function() {
                previewImage(this, 'thirdPreview', 'thirdStatus');
            });
            document.getElementById('fourthFile').addEventListener('change', function() {
                previewImage(this, 'fourthPreview', 'fourthStatus');
            });
            
            // 支付类型选择事件
            document.getElementById('thirdType').addEventListener('change', updateThirdType);
            document.getElementById('fourthType').addEventListener('change', updateFourthType);
            
            // 自定义名称输入事件
            document.getElementById('thirdCustomName').addEventListener('input', updateThirdType);
            document.getElementById('fourthCustomName').addEventListener('input', updateFourthType);
            
            // QQ样式选择事件
            document.querySelectorAll('input[name="qqStyle"]').forEach(radio => {
                radio.addEventListener('change', function() {
                    if (this.checked) {
                        qqStyle = this.value;
                        document.querySelectorAll('.style-option').forEach(opt => {
                            opt.classList.remove('active');
                        });
                        this.parentElement.classList.add('active');
                    }
                });
            });
            
            // 生成和下载按钮事件
            document.getElementById('generateBtn').addEventListener('click', generateCombinedQR);
            document.getElementById('downloadBtn').addEventListener('click', downloadCombinedQR);
            
            // 图片大小调整功能
            document.querySelectorAll('.size-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    document.querySelectorAll('.size-btn').forEach(b => b.classList.remove('active'));
                    this.classList.add('active');
                    currentSize = parseInt(this.dataset.size);
                    document.getElementById('sizeSlider').value = currentSize;
                    document.getElementById('sizeValue').textContent = currentSize + 'px';
                    
                    // 重新生成图片
                    if (layoutMode === 'two-grid' && wechatQR && alipayQR) {
                        renderTwoGridImage(wechatQR, alipayQR, currentSize);
                    } else if (layoutMode === 'three-grid' && wechatQR && alipayQR && thirdQR) {
                        renderThreeGridImage(wechatQR, alipayQR, thirdQR, currentSize);
                    } else if (layoutMode === 'four-grid' && wechatQR && alipayQR && thirdQR && fourthQR) {
                        renderFourGridImage(wechatQR, alipayQR, thirdQR, fourthQR, currentSize);
                    }
                });
            });
            
            // 滑块调整大小
            document.getElementById('sizeSlider').addEventListener('input', function() {
                currentSize = parseInt(this.value);
                document.getElementById('sizeValue').textContent = currentSize + 'px';
                
                // 更新按钮状态
                document.querySelectorAll('.size-btn').forEach(btn => {
                    if (parseInt(btn.dataset.size) === currentSize) {
                        btn.classList.add('active');
                    } else {
                        btn.classList.remove('active');
                    }
                });
                
                // 重新生成图片
                if (layoutMode === 'two-grid' && wechatQR && alipayQR) {
                    renderTwoGridImage(wechatQR, alipayQR, currentSize);
                } else if (layoutMode === 'three-grid' && wechatQR && alipayQR && thirdQR) {
                    renderThreeGridImage(wechatQR, alipayQR, thirdQR, currentSize);
                } else if (layoutMode === 'four-grid' && wechatQR && alipayQR && thirdQR && fourthQR) {
                    renderFourGridImage(wechatQR, alipayQR, thirdQR, fourthQR, currentSize);
                }
            });
            
            // 确保初始状态为二格模式
            setLayoutMode('two-grid');
        };
        
        // 设置布局模式
        function setLayoutMode(mode) {
            console.log('设置布局模式为:', mode);
            layoutMode = mode;
            
            // 显示/隐藏相关元素
            const thirdElements = document.querySelectorAll('.third-code');
            const fourthElements = document.querySelectorAll('.fourth-code');
            
            // 隐藏所有第三方和第四方相关元素
            thirdElements.forEach(el => el.classList.add('hidden'));
            fourthElements.forEach(el => el.classList.add('hidden'));
            
            // 隐藏所有信息框
            document.getElementById('twoGridInfo').classList.add('hidden');
            document.getElementById('threeGridInfo').classList.add('hidden');
            document.getElementById('fourGridInfo').classList.add('hidden');
            
            // 根据模式显示相应元素
            if (mode === 'two-grid') {
                document.getElementById('twoGridInfo').classList.remove('hidden');
                document.getElementById('resultTitle').textContent = '您的二格收款码';
            } 
            else if (mode === 'three-grid') {
                thirdElements.forEach(el => el.classList.remove('hidden'));
                document.getElementById('threeGridInfo').classList.remove('hidden');
                document.getElementById('resultTitle').textContent = '您的三格收款码';
            } 
            else if (mode === 'four-grid') {
                thirdElements.forEach(el => el.classList.remove('hidden'));
                fourthElements.forEach(el => el.classList.remove('hidden'));
                document.getElementById('fourGridInfo').classList.remove('hidden');
                document.getElementById('resultTitle').textContent = '您的四格收款码';
            }
            
            // 检查生成按钮状态
            checkEnableGenerate();
        }
        
        // 更新第三方支付类型
        function updateThirdType() {
            thirdPayType = document.getElementById('thirdType').value;
            const titleElem = document.getElementById('thirdTypeTitle');
            const placeholderText = document.getElementById('thirdPlaceholderText');
            const customNameInput = document.getElementById('thirdCustomName');
            const customNameContainer = document.getElementById('thirdCustomNameContainer');
            const qqStyleSelector = document.getElementById('qqStyleSelector');
            
            // 处理自定义名称输入框和QQ样式选择器的显示/隐藏
            customNameContainer.classList.add('hidden');
            qqStyleSelector.classList.add('hidden');
            
            if (thirdPayType === 'custom') {
                customNameContainer.classList.remove('hidden');
                if (customNameInput.value.trim() !== '') {
                    titleElem.textContent = customNameInput.value.trim() + '收款码';
                    placeholderText.textContent = '点击上传' + customNameInput.value.trim() + '收款码';
                    thirdCustomPayName = customNameInput.value.trim();
                } else {
                    titleElem.textContent = '自定义收款码';
                    placeholderText.textContent = '点击上传自定义收款码';
                    thirdCustomPayName = '自定义';
                }
            } else if (thirdPayType === 'qq') {
                qqStyleSelector.classList.remove('hidden');
                titleElem.textContent = 'QQ收款码';
                placeholderText.textContent = '点击上传QQ收款码';
                thirdCustomPayName = null;
            } else if (thirdPayType === 'unionpay') {
                titleElem.textContent = '云闪付收款码';
                placeholderText.textContent = '点击上传云闪付收款码';
                thirdCustomPayName = null;
            }
        }
        
        // 更新第二个第三方支付类型
        function updateFourthType() {
            fourthPayType = document.getElementById('fourthType').value;
            const titleElem = document.getElementById('fourthTypeTitle');
            const placeholderText = document.getElementById('fourthPlaceholderText');
            const customNameInput = document.getElementById('fourthCustomName');
            const customNameContainer = document.getElementById('fourthCustomNameContainer');
            
            // 处理自定义名称输入框显示/隐藏
            customNameContainer.classList.add('hidden');
            
            if (fourthPayType === 'custom') {
                customNameContainer.classList.remove('hidden');
                if (customNameInput.value.trim() !== '') {
                    titleElem.textContent = customNameInput.value.trim() + '收款码';
                    placeholderText.textContent = '点击上传' + customNameInput.value.trim() + '收款码';
                    fourthCustomPayName = customNameInput.value.trim();
                } else {
                    titleElem.textContent = '自定义收款码';
                    placeholderText.textContent = '点击上传自定义收款码';
                    fourthCustomPayName = '自定义';
                }
            } else {
                if (fourthPayType === 'unionpay') {
                    titleElem.textContent = '云闪付收款码';
                    placeholderText.textContent = '点击上传云闪付收款码';
                    fourthCustomPayName = null;
                } else if (fourthPayType === 'qq') {
                    titleElem.textContent = 'QQ收款码';
                    placeholderText.textContent = '点击上传QQ收款码';
                    fourthCustomPayName = null;
                }
            }
        }
        
        // 预览上传的图片并解码二维码
        function previewImage(input, previewId, statusId) {
            if (input.files && input.files[0]) {
                const reader = new FileReader();
                const preview = document.getElementById(previewId);
                const statusDiv = document.getElementById(statusId);
                const uploadArea = input.parentElement;
                
                // 显示加载状态
                statusDiv.textContent = '正在读取图片...';
                statusDiv.className = 'qr-status';
                
                reader.onload = function(e) {
                    preview.src = e.target.result;
                    preview.style.display = 'block';
                    
                    // 隐藏上传提示
                    uploadArea.querySelector('.upload-icon').style.display = 'none';
                    uploadArea.querySelector('.upload-text').style.display = 'none';
                    uploadArea.querySelector('.upload-hint').style.display = 'none';
                    
                    // 保存图片到相应变量
                    if (previewId === 'wechatPreview') {
                        wechatImg = e.target.result;
                    } else if (previewId === 'alipayPreview') {
                        alipayImg = e.target.result;
                    } else if (previewId === 'thirdPreview') {
                        thirdImg = e.target.result;
                    } else if (previewId === 'fourthPreview') {
                        fourthImg = e.target.result;
                    }
                    
                    // 解析二维码
                    const img = new Image();
                    img.onload = function() {
                        // 创建临时canvas来处理图片
                        const canvas = document.createElement('canvas');
                        const ctx = canvas.getContext('2d');
                        
                        // 设置canvas大小
                        canvas.width = img.width;
                        canvas.height = img.height;
                        
                        // 绘制图片到canvas
                        ctx.drawImage(img, 0, 0);
                        
                        // 获取图像数据
                        const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
                        
                        // 使用jsQR库解析二维码
                        const code = jsQR(imageData.data, imageData.width, imageData.height);
                        
                        if (code) {
                            // 二维码解析成功
                            statusDiv.textContent = '✓ 二维码有效';
                            statusDiv.className = 'qr-status status-valid';
                            
                            // 保存二维码数据而不显示内容
                            if (previewId === 'wechatPreview') {
                                wechatData = code.data;
                            } else if (previewId === 'alipayPreview') {
                                alipayData = code.data;
                            } else if (previewId === 'thirdPreview') {
                                thirdData = code.data;
                            } else if (previewId === 'fourthPreview') {
                                fourthData = code.data;
                            }
                        } else {
                            // 二维码解析失败
                            statusDiv.textContent = '⚠ 无法识别二维码';
                            statusDiv.className = 'qr-status status-invalid';
                            
                            // 添加重试按钮
                            let retryButton = document.createElement('button');
                            retryButton.textContent = '重新上传';
                            retryButton.className = 'btn';
                            retryButton.style.cssText = 'margin-top:8px; padding:5px 10px; font-size:12px;';
                            
                            // 清除旧的重试按钮(如果有)
                            const oldRetryBtn = statusDiv.parentNode.querySelector('.retry-btn');
                            if (oldRetryBtn) {
                                oldRetryBtn.remove();
                            }
                            
                            retryButton.classList.add('retry-btn');
                            
                            // 添加新的重试按钮
                            statusDiv.parentNode.appendChild(retryButton);
                            
                            // 重置相应的数据变量
                            if (previewId === 'wechatPreview') {
                                wechatData = null;
                            } else if (previewId === 'alipayPreview') {
                                alipayData = null;
                            } else if (previewId === 'thirdPreview') {
                                thirdData = null;
                            } else if (previewId === 'fourthPreview') {
                                fourthData = null;
                            }
                            
                            // 添加重试按钮的点击事件
                            retryButton.addEventListener('click', function() {
                                // 重置显示元素
                                preview.style.display = 'none';
                                uploadArea.querySelector('.upload-icon').style.display = 'block';
                                uploadArea.querySelector('.upload-text').style.display = 'block';
                                uploadArea.querySelector('.upload-hint').style.display = 'block';
                                statusDiv.textContent = '';
                                
                                // 移除重试按钮
                                this.remove();
                                
                                // 重置文件输入
                                input.value = '';
                                
                                // 检查生成按钮状态
                                checkEnableGenerate();
                            });
                        }
                        
                        // 检查生成按钮状态
                        checkEnableGenerate();
                    };
                    
                    img.onerror = function() {
                        // 图片加载失败
                        statusDiv.textContent = '⚠ 图片无效';
                        statusDiv.className = 'qr-status status-invalid';
                        preview.style.display = 'none';
                        uploadArea.querySelector('.upload-icon').style.display = 'block';
                        uploadArea.querySelector('.upload-text').style.display = 'block';
                        uploadArea.querySelector('.upload-hint').style.display = 'block';
                        
                        // 重置文件输入，允许重新上传
                        input.value = '';
                    };
                    
                    img.src = e.target.result;
                };
                
                reader.readAsDataURL(input.files[0]);
            }
        }
        
        // 检查是否可以启用生成按钮
        function checkEnableGenerate() {
            const generateBtn = document.getElementById('generateBtn');
            if (layoutMode === 'two-grid') {
                generateBtn.disabled = !(wechatImg && alipayImg && wechatData && alipayData);
            } else if (layoutMode === 'three-grid') {
                generateBtn.disabled = !(wechatImg && alipayImg && thirdImg && wechatData && alipayData && thirdData);
            } else if (layoutMode === 'four-grid') {
                generateBtn.disabled = !(wechatImg && alipayImg && thirdImg && fourthImg && 
                    wechatData && alipayData && thirdData && fourthData);
            }
        }
        
        // 生成新的二维码
        function generateNewQRCode(data, size) {
            return new Promise((resolve, reject) => {
                QRCode.toDataURL(data, {
                    width: size,
                    margin: 1,
                    color: {
                        dark: '#000000',
                        light: '#FFFFFF'
                    }
                }, function(err, url) {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(url);
                    }
                });
            });
        }
        
        // 生成收款码
        async function generateCombinedQR() {
            try {
                document.getElementById('error').textContent = '';
                document.getElementById('error').classList.add('hidden');
                
                // 检查是否成功解码
                if (layoutMode === 'two-grid') {
                    if (!wechatData || !alipayData) {
                        showError('无法解码二维码内容，请上传清晰的收款码图片');
                        return;
                    }
                } else if (layoutMode === 'three-grid') {
                    if (!wechatData || !alipayData || !thirdData) {
                        showError('无法解码二维码内容，请上传清晰的收款码图片');
                        return;
                    }
                } else if (layoutMode === 'four-grid') {
                    if (!wechatData || !alipayData || !thirdData || !fourthData) {
                        showError('无法解码二维码内容，请上传清晰的收款码图片');
                        return;
                    }
                }
                
                // 重新生成二维码
                const qrCodeSize = 400;
                
                // 异步生成新的二维码
                wechatQR = await generateNewQRCode(wechatData, qrCodeSize);
                alipayQR = await generateNewQRCode(alipayData, qrCodeSize);
                
                if (layoutMode === 'three-grid') {
                    thirdQR = await generateNewQRCode(thirdData, qrCodeSize);
                    renderThreeGridImage(wechatQR, alipayQR, thirdQR, currentSize);
                } else if (layoutMode === 'four-grid') {
                    thirdQR = await generateNewQRCode(thirdData, qrCodeSize);
                    fourthQR = await generateNewQRCode(fourthData, qrCodeSize);
                    renderFourGridImage(wechatQR, alipayQR, thirdQR, fourthQR, currentSize);
                } else {
                    renderTwoGridImage(wechatQR, alipayQR, currentSize);
                }
                
            } catch (error) {
                showError('生成失败: ' + error.message);
                console.error('拼接收款码错误:', error);
            }
        }
        
        // 显示错误信息
        function showError(message) {
            const errorElem = document.getElementById('error');
            errorElem.textContent = message;
            errorElem.classList.remove('hidden');
        }
        
        // 渲染二格收款码
        function renderTwoGridImage(wechatQRUrl, alipayQRUrl, size) {
            const wechatImage = new Image();
            const alipayImage = new Image();
            
            wechatImage.onload = function() {
                alipayImage.onload = function() {
                    const canvas = document.createElement('canvas');
                    const ctx = canvas.getContext('2d');
                    
                    // 设置画布大小
                    canvas.width = size;
                    canvas.height = size;
                    
                    // 填充白色背景
                    ctx.fillStyle = '#ffffff';
                    ctx.fillRect(0, 0, size, size);
                    
                    // 上半部分 - 微信支付（绿色背景）
                    ctx.fillStyle = '#07C160';
                    ctx.fillRect(0, 0, size, size/2);
                    
                    // 下半部分 - 支付宝（蓝色背景）
                    ctx.fillStyle = '#1677FF';
                    ctx.fillRect(0, size/2, size, size/2);
                    
                    // 定义二维码尺寸和位置（稍微缩小）
                    const qrSize = size * 0.35;
                    const qrMargin = size * 0.075;
                    
                    // 绘制微信收款码（上半部分左侧）
                    ctx.drawImage(wechatImage, 
                        qrMargin,
                        (size/2 - qrSize)/2,
                        qrSize, qrSize);
                    
                    // 绘制支付宝收款码（下半部分右侧）
                    ctx.drawImage(alipayImage, 
                        size - qrSize - qrMargin,
                        size/2 + (size/2 - qrSize)/2,
                        qrSize, qrSize);
                    
                    // 文字样式
                    ctx.fillStyle = '#ffffff';
                    const fontSize = size/14;
                    ctx.font = 'bold ' + fontSize + 'px sans-serif';
                    ctx.textBaseline = 'middle';
                    
                    // 上半部分标题文字（微信支付）- 放右侧
                    ctx.textAlign = 'left';
                    ctx.fillText('微信支付', size/2 + qrMargin, (size/4) - fontSize);
                    
                    // 微信收款码下方提示文字
                    ctx.font = 'bold ' + (fontSize*0.8) + 'px sans-serif';
                    ctx.fillText('打开微信扫一扫', size/2 + qrMargin, (size/4) + fontSize);
                    
                    // 下半部分标题文字（支付宝）- 放左侧
                    ctx.font = 'bold ' + fontSize + 'px sans-serif';
                    ctx.fillText('支付宝', qrMargin, size/2 + (size/4) - fontSize);
                    
                    // 支付宝收款码下方提示文字
                    ctx.font = 'bold ' + (fontSize*0.8) + 'px sans-serif';
                    ctx.fillText('打开支付宝扫一扫', qrMargin, size/2 + (size/4) + fontSize);
                    
                    // 转换为图片并显示
                    const combinedImage = canvas.toDataURL('image/png');
                    displayResultImage(combinedImage);
                };
                alipayImage.src = alipayQRUrl;
            };
            wechatImage.src = wechatQRUrl;
        }
        
        // 渲染三格收款码
        function renderThreeGridImage(wechatQRUrl, alipayQRUrl, thirdQRUrl, size) {
            const wechatImage = new Image();
            const alipayImage = new Image();
            const thirdImage = new Image();
            
            wechatImage.onload = function() {
                alipayImage.onload = function() {
                    thirdImage.onload = function() {
                        const canvas = document.createElement('canvas');
                        const ctx = canvas.getContext('2d');
                        
                        // 设置画布大小
                        canvas.width = size;
                        canvas.height = size;
                        
                        // 填充白色背景
                        ctx.fillStyle = '#ffffff';
                        ctx.fillRect(0, 0, size, size);
                        
                        // 修改分区比例：上部区域占60%，底部区域占40%
                        const topHeight = size * 0.6;
                        const bottomHeight = size * 0.4;
                        
                        // 上半部分左侧 - 微信支付（绿色背景）
                        ctx.fillStyle = '#07C160';
                        ctx.fillRect(0, 0, size/2, topHeight);
                        
                        // 上半部分右侧 - 支付宝（蓝色背景）
                        ctx.fillStyle = '#1677FF';
                        ctx.fillRect(size/2, 0, size/2, topHeight);
                        
                        // 下半部分 - 第三方支付（根据类型设置颜色）
                        if (thirdPayType === 'unionpay') {
                            ctx.fillStyle = '#FA6F63';
                        } else if (thirdPayType === 'qq') {
                            switch(qqStyle) {
                                case 'purple': ctx.fillStyle = '#6A11CB'; break;
                                case 'green': ctx.fillStyle = '#3CB371'; break;
                                case 'dark': ctx.fillStyle = '#333333'; break;
                                default: ctx.fillStyle = '#12B7F5';
                            }
                        } else {
                            ctx.fillStyle = '#FF9800';
                        }
                        ctx.fillRect(0, topHeight, size, bottomHeight);
                        
                        // 定义二维码尺寸和位置
                        const qrMargin = size * 0.05;
                        const qrSizeTop = size * 0.3;
                        const qrSizeBottom = size * 0.28;
                        
                        // 减小垂直偏移量，让上部二维码位置更协调
                        const verticalOffset = size * 0.015;
                        
                        // 调整上方二维码位置计算方式
                        const topQrY = topHeight/2 - qrSizeTop/2 - verticalOffset;
                        
                        // 绘制微信收款码（左上区域）- 尺寸更大
                        ctx.drawImage(wechatImage, 
                            (size/2 - qrSizeTop)/2,
                            topQrY,
                            qrSizeTop, qrSizeTop);
                        
                        // 绘制支付宝收款码（右上区域）- 尺寸更大
                        ctx.drawImage(alipayImage, 
                            size/2 + (size/2 - qrSizeTop)/2,
                            topQrY,
                            qrSizeTop, qrSizeTop);
                        
                        // 绘制第三方收款码（底部区域）- 靠左放置
                        ctx.drawImage(thirdImage, 
                            qrMargin * 2,
                            topHeight + (bottomHeight - qrSizeBottom)/2,
                            qrSizeBottom, qrSizeBottom);
                        
                        // 文字样式
                        ctx.fillStyle = '#ffffff';
                        const fontSize = size/20;
                        ctx.font = 'bold ' + fontSize + 'px sans-serif';
                        ctx.textBaseline = 'middle';
                        ctx.textAlign = 'center';
                        
                        // 微信提示文字 - 移到二维码下方，适当调整位置
                        ctx.fillText('微信支付', size/4, 
                            topQrY + qrSizeTop + fontSize);
                        
                        // 支付宝提示文字 - 移到二维码下方，适当调整位置
                        ctx.fillText('支付宝', size*3/4, 
                            topQrY + qrSizeTop + fontSize);
                        
                        // 第三方支付文字 - 移到右侧与二维码平行
                        let thirdTypeText = thirdPayType === 'unionpay' ? '云闪付' : 
                                         (thirdPayType === 'qq' ? 'QQ支付' : thirdCustomPayName + '支付');
                        ctx.textAlign = 'left';
                        const thirdTextX = qrMargin * 2 + qrSizeBottom + qrMargin * 2;
                        const thirdTextY = topHeight + bottomHeight/2;
                        
                        // 绘制第三方支付文字
                        ctx.font = 'bold ' + (fontSize*1.2) + 'px sans-serif';
                        ctx.fillText(thirdTypeText, thirdTextX, thirdTextY - fontSize);
                        
                        // 添加扫码提示
                        ctx.font = 'bold ' + (fontSize*0.8) + 'px sans-serif';
                        ctx.fillText('扫一扫', thirdTextX, thirdTextY + fontSize);
                        
                        // 转换为图片并显示
                        const combinedImage = canvas.toDataURL('image/png');
                        displayResultImage(combinedImage);
                    };
                    thirdImage.src = thirdQRUrl;
                };
                alipayImage.src = alipayQRUrl;
            };
            wechatImage.src = wechatQRUrl;
        }
        
        // 渲染四格收款码
        function renderFourGridImage(wechatQRUrl, alipayQRUrl, thirdQRUrl, fourthQRUrl, size) {
            const wechatImage = new Image();
            const alipayImage = new Image();
            const thirdImage = new Image();
            const fourthImage = new Image();
            
            wechatImage.onload = function() {
                alipayImage.onload = function() {
                    thirdImage.onload = function() {
                        fourthImage.onload = function() {
                            const canvas = document.createElement('canvas');
                            const ctx = canvas.getContext('2d');
                            
                            // 设置画布大小
                            canvas.width = size;
                            canvas.height = size;
                            
                            // 填充白色背景
                            ctx.fillStyle = '#ffffff';
                            ctx.fillRect(0, 0, size, size);
                            
                            // 左上角 - 微信支付（绿色背景）
                            ctx.fillStyle = '#07C160';
                            ctx.fillRect(0, 0, size/2, size/2);
                            
                            // 右上角 - 支付宝（蓝色背景）
                            ctx.fillStyle = '#1677FF';
                            ctx.fillRect(size/2, 0, size/2, size/2);
                            
                            // 左下角 - 第三方支付
                            if (thirdPayType === 'unionpay') {
                                ctx.fillStyle = '#FA6F63';
                            } else if (thirdPayType === 'qq') {
                                switch(qqStyle) {
                                    case 'purple': ctx.fillStyle = '#6A11CB'; break;
                                    case 'green': ctx.fillStyle = '#3CB371'; break;
                                    case 'dark': ctx.fillStyle = '#333333'; break;
                                    default: ctx.fillStyle = '#12B7F5';
                                }
                            } else {
                                ctx.fillStyle = '#FF9800';
                            }
                            ctx.fillRect(0, size/2, size/2, size/2);
                            
                            // 右下角 - 第四方支付
                            if (fourthPayType === 'unionpay') {
                                ctx.fillStyle = '#FA6F63';
                            } else if (fourthPayType === 'qq') {
                                ctx.fillStyle = '#12B7F5';
                            } else {
                                ctx.fillStyle = '#9C27B0';
                            }
                            ctx.fillRect(size/2, size/2, size/2, size/2);
                            
                            // 定义二维码尺寸和位置 - 调整位置使二维码更靠上
                            const qrSize = size * 0.32;
                            const verticalOffset = size * 0.06;
                            
                            // 绘制微信收款码（左上角）- 向上移动
                            ctx.drawImage(wechatImage, 
                                (size/2 - qrSize)/2,
                                (size/2 - qrSize)/2 - verticalOffset,
                                qrSize, qrSize);
                            
                            // 绘制支付宝收款码（右上角）- 向上移动
                            ctx.drawImage(alipayImage, 
                                size/2 + (size/2 - qrSize)/2,
                                (size/2 - qrSize)/2 - verticalOffset,
                                qrSize, qrSize);
                            
                            // 绘制第三方收款码（左下角）- 向上移动
                            ctx.drawImage(thirdImage, 
                                (size/2 - qrSize)/2,
                                size/2 + (size/2 - qrSize)/2 - verticalOffset,
                                qrSize, qrSize);
                            
                            // 绘制第四方收款码（右下角）- 向上移动
                            ctx.drawImage(fourthImage, 
                                size/2 + (size/2 - qrSize)/2,
                                size/2 + (size/2 - qrSize)/2 - verticalOffset,
                                qrSize, qrSize);
                            
                            // 文字样式
                            ctx.fillStyle = '#ffffff';
                            const fontSize = size/24;
                            ctx.font = 'bold ' + fontSize + 'px sans-serif';
                            ctx.textBaseline = 'middle';
                            ctx.textAlign = 'center';
                            
                            // 微信标识 - 移到二维码下方
                            ctx.fillText('微信支付', size/4, (size/2 - qrSize)/2 + qrSize - verticalOffset + fontSize*2);
                            
                            // 支付宝标识 - 移到二维码下方
                            ctx.fillText('支付宝', size*3/4, (size/2 - qrSize)/2 + qrSize - verticalOffset + fontSize*2);
                            
                            // 第三方标识 - 移到二维码下方
                            let thirdTypeText = thirdPayType === 'unionpay' ? '云闪付' : 
                                             (thirdPayType === 'qq' ? 'QQ支付' : thirdCustomPayName + '支付');
                            ctx.fillText(thirdTypeText, size/4, size/2 + (size/2 - qrSize)/2 + qrSize - verticalOffset + fontSize*2);
                            
                            // 第四方标识 - 移到二维码下方
                            let fourthTypeText = fourthPayType === 'unionpay' ? '云闪付' : 
                                              (fourthPayType === 'qq' ? 'QQ支付' : fourthCustomPayName + '支付');
                            ctx.fillText(fourthTypeText, size*3/4, size/2 + (size/2 - qrSize)/2 + qrSize - verticalOffset + fontSize*2);
                            
                            // 转换为图片并显示
                            const combinedImage = canvas.toDataURL('image/png');
                            displayResultImage(combinedImage);
                        };
                        fourthImage.src = fourthQRUrl;
                    };
                    thirdImage.src = thirdQRUrl;
                };
                alipayImage.src = alipayQRUrl;
            };
            wechatImage.src = wechatQRUrl;
        }
        
        // 显示结果图片
        function displayResultImage(imageUrl) {
            const container = document.getElementById('combinedQRCode');
            container.innerHTML = `<img src="${imageUrl}" alt="${layoutMode.replace('-', ' ')}收款码">`;
        }
        
        // 下载拼接后的收款码
        function downloadCombinedQR() {
            const img = document.querySelector('#combinedQRCode img');
            if (!img) return;
            
            const link = document.createElement('a');
            link.href = img.src;
            const filename = layoutMode === 'two-grid' ? '二格收款码.png' : (layoutMode === 'three-grid' ? '三格收款码.png' : '四格收款码.png');
            link.download = filename;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    </script>
</body>
</html>